#include "DS1302.h"
#include "Delay.h"


char DS1302_Time [] = {24, 7, 2, 22, 35, 2, 2};



#define DS1302_SECOND 	0x80
#define DS1302_MINUTE 	0x82
#define DS1302_HOUR 	0x84
#define DS1302_DATE 	0x86
#define DS1302_MONTH 	0x88
#define DS1302_DAY 		0x8A
#define DS1302_YEAR 	0x8C
#define DS1302_WP 		0x8E

/**
  * @brief  
  * @param  
  * @retval 
  */
void DS1302_Init(void)
{
	DS1302_CE = 0;
	DS1302_SCLK = 0;
}

/**
  * @brief  
  * @param  
  * @retval 
  */
void DS1302_WriteByte(unsigned char Command, unsigned char Data)
{
	unsigned char i = 0;
	
	DS1302_CE = 1;
	
	
	for(i=0; i<8; i++)
	{
		DS1302_IO = Command & (0x01 << i);
		DS1302_SCLK = 1;
		////51单片机的速度比较慢，不需要延时
		DS1302_SCLK	= 0;
	}

	for(i=0; i<8; i++)
	{
		DS1302_IO = Data & (0x01 << i);
		DS1302_SCLK = 1;
		DS1302_SCLK	= 0;
	}
	
	DS1302_CE = 0;
}


/**
  * @brief  
  * @param  
  * @retval 
  */
unsigned char DS1302_ReadByte(unsigned char Command)
{
	unsigned char i = 0;
	unsigned char Data = 0;
	
	DS1302_CE = 1;
	
	
	Command |= 0x01;
	for(i=0; i<8; i++)
	{
		DS1302_IO = Command & (0x01 << i);
		DS1302_SCLK	= 0;
		DS1302_SCLK = 1;
	}
	
	
	/* 为什么需要这一句??*/
	//DS1302_IO = 0;
	
	for(i=0; i<8; i++)
	{
		DS1302_SCLK = 1;	
		DS1302_SCLK	= 0;
		if(DS1302_IO)
		{
			Data |= (0x01 << i);
		}
	}

	/* 为什么需要这一句??*/
	DS1302_IO = 0;			//加上这一句否则会随机读取出错误值
	
	DS1302_CE = 0;
	
	return Data;
}

/**
  * @brief  
  * @param  
  * @retval 
  */
void DS1302_SetTime(void)
{
	//关闭DS1302写保护
	DS1302_WriteByte(DS1302_WP, 0x00);
	
	
	DS1302_WriteByte(DS1302_YEAR, 	DS1302_Time[0]/10*16 + DS1302_Time[0]%10);
	DS1302_WriteByte(DS1302_MONTH, 	DS1302_Time[1]/10*16 + DS1302_Time[1]%10);
	DS1302_WriteByte(DS1302_DATE, 	DS1302_Time[2]/10*16 + DS1302_Time[2]%10);
	DS1302_WriteByte(DS1302_HOUR, 	DS1302_Time[3]/10*16 + DS1302_Time[3]%10);
	DS1302_WriteByte(DS1302_MINUTE, DS1302_Time[4]/10*16 + DS1302_Time[4]%10);
	DS1302_WriteByte(DS1302_SECOND, DS1302_Time[5]/10*16 + DS1302_Time[5]%10);
	DS1302_WriteByte(DS1302_DAY, 	DS1302_Time[6]/10*16 + DS1302_Time[6]%10);
	
	
	//打开DS1302写保护
	//DS1302_WriteByte(DS1302_WP, 0x80);
}

/**
  * @brief  
  * @param  
  * @retval 
  */
void DS1302_ReadTime(void)
{
	unsigned char temp;
	temp = DS1302_ReadByte(DS1302_YEAR);
	DS1302_Time[0] = temp/16*10 + temp%16;
	
	temp = DS1302_ReadByte(DS1302_MONTH);
	DS1302_Time[1] = temp/16*10 + temp%16;
	
	temp = DS1302_ReadByte(DS1302_DATE);
	DS1302_Time[2] = temp/16*10 + temp%16;
	
	temp = DS1302_ReadByte(DS1302_HOUR);
	DS1302_Time[3] = temp/16*10 + temp%16;
	
	temp = DS1302_ReadByte(DS1302_MINUTE);
	DS1302_Time[4] = temp/16*10 + temp%16;
	
	temp = DS1302_ReadByte(DS1302_SECOND);
	DS1302_Time[5] = temp/16*10 + temp%16;
	
	temp = DS1302_ReadByte(DS1302_DAY);
	DS1302_Time[6] = temp/16*10 + temp%16;
}